﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZK.BLL;
using ZK.Entity;
using ZK.MyControl;

namespace ZK.Client.WinForm
{
    public partial class FrmCodeRule : Form
    {
        public FrmCodeRule()
        {
            InitializeComponent();
        }
        BindingList<CodeRule> bindinglist = new BindingList<CodeRule>();
        BindingSource bindingSource = new BindingSource();
        private void FrmCodeRule_Load(object sender, EventArgs e)
        {
            bindingSource.DataSource = bindinglist;
            dataView1.DataSource = bindingSource;
            AddColumns();
            LoadData();
        }



        private void AddColumns()
        {
 
            dataView1.Columns.Add(DataGridColumnHelper.ComboBoxColumnCreate(typeof(CodeRule) ,nameof(CodeRule.CodeRuleType),Enum.GetValues(typeof(CodeRuleType))));
            dataView1.Columns.Add(DataGridColumnHelper.TextBoxColumnCreate(typeof(CodeRule),nameof(CodeRule.CodeRuleLen)));
            dataView1.Columns.Add(DataGridColumnHelper.TextBoxColumnCreate(typeof(CodeRule), nameof(CodeRule.DefaultValue)));
        }


        private void LoadData()
        {
            bindinglist.Clear();

            var list = CodeRuleBLL.Instance.GetList();
            if (list != null && list.Count > 0)
            {
                list.ForEach(s=>
                {
                    bindinglist.Add(s);
                } );
            }

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            bindinglist.Add(new CodeRule() {  CodeRuleLen=1});
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dataView1.CurrentCell != null && dataView1.CurrentCell.RowIndex > -1)
            {
                bindinglist.RemoveAt(dataView1.CurrentCell.RowIndex);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var list = bindinglist.ToList();

            list.ForEach(s=> {

                s.Id = CodeRuleBLL.Instance.GetNewID();
            });

            if (CodeRuleBLL.Instance.InsertList(list))
            {
                MessageBox.Show("保存成功");
            }
            else {
                MessageBox.Show("保存失败");
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            var list = bindinglist.ToList();

            string buildcode=CodeRuleBLL.Instance.BuildCode();

            MessageBox.Show(buildcode);
        }
    }
}
